import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/ball_pulse_footer.dart';
import 'package:flutter_easyrefresh/ball_pulse_header.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter_juwo/common/common_index.dart' as prefix0;
import 'package:flutter_juwo/provider/CheckAccountModel.dart';
import 'package:flutter_juwo/provider/UserModel.dart';
import 'package:flutter_juwo/ui/controller/NetUtils.dart';
import 'package:flutter_juwo/ui/custom/NotLoginPage.dart';
import 'package:flutter_juwo/ui/custom/judje_dialog.dart';
import 'package:flutter_juwo/ui/custom/noData.dart';
import 'package:flutter_juwo/ui/custom/real_rich_text.dart';
import 'package:flutter_juwo/ui/res/shared_preferences_keys.dart';
import 'package:flutter_juwo/ui/utils/sp_util.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';
import 'package:provider/provider.dart';

import 'model/task_list_entity.dart';
import 'model/testaccount_entity.dart';

class TaskList extends StatefulWidget {
  int index;

  TaskList({int index = 0}) {
    this.index = index;
  }

  @override
  _TaskListState createState() => _TaskListState();
}

class _TaskListState extends State<TaskList> {
  MyPageState ps = MyPageState.LOADING;
  EasyRefreshController _easyRefreshController = EasyRefreshController();
  TaskListEntity _entity = null;

  ///当前码
  int _currentPage = 1;

  ///页数默认为1 通过 总数 计算得来
  int _pages = 1;
  bool isLogin;

  ///一页 20 条数据
  int _itemNum = 20;

  bool isZb = false;

  /// 是否有直播

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isLogin = NetUtils.isLogin();
    if (isLogin) {
      ///获取数据
      this.getData();
    } else {
      ps = MyPageState.NOT_LOGIN;
    }
  }

  @override
  void deactivate() {
    // TODO: implement deactivate
    super.deactivate();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _easyRefreshController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (isLogin && Provider.of<CheckAccountModel>(context).value) {
      Provider.of<CheckAccountModel>(context).update(false);

      ///获取是否添加相关账号
      this.getAccount();
    }

    return Scaffold(
      backgroundColor: Colours.c243,
      body: Consumer<UserModel>(
        builder: (context, UserModel userModel, _) {
          return getContent();
        },
      ),
    );
  }

  getContent() {
    ///1.没有登录
    if (SpUtil.getString(SpKeys.userToken).isEmpty) {
      ps = MyPageState.NOT_LOGIN;
    } else {
      if (ps != MyPageState.NOT_DATA) {
        ps = MyPageState.HAVE_DATA;
      }
    }

    ///正在加载
    if (ps == MyPageState.LOADING) {
      return LoadingPage();
    }

    ///没有数据
    if (ps == MyPageState.NOT_DATA) {
      if (isZb) {
        return _ContentWithZb(NoData(getNodata));
      } else {
        return NoData(getNodata);
      }
    }

    if (ps == MyPageState.NOT_LOGIN) {
      return NotLoginPage();
    }

    if (ps == MyPageState.HAVE_DATA) {
      if (null == _entity) {
        getData();
        return LoadingPage();
      }

      if (isZb) {
        return _ContentWithZb(_listView());
      } else {
        return _listView();
      }
    }

    return NoData(getData);
  }

  ///没有数据
  void noData() {
    ps = MyPageState.NOT_DATA;
    setState(() {});
  }

  ///有数据
  void haveData() {
    ps = MyPageState.HAVE_DATA;
    setState(() {});
  }

  getNodata() {
    ps = MyPageState.LOADING;
    setState(() {});
    getData();
  }

  Future getData({int page = 1}) async {
    FormData params = getFormData(page);
    DioManager.getInstance().get(Api.TASK_GETLIST, params, (json) {
      TaskListEntity data = TaskListEntity.fromJson(json);
      visible = false;

      ///第一次加载
      if (page == 1) {
        if (null == data) {
          this.noData();
          return;
        }
        if (data.code != 200) {
          this.noData();
          return;
        }
        if (null == data.data.result || data.data.result.length <= 0) {
          this.noData();
          return;
        }
        _entity = data;
        _pages = data.data.totalPage;

        ///这个版本 不处理直播单 ，
          if(null!=data.data.isZb&&null!=data.data.isZb.zbtype){
          isZb = data.data.isZb.zbtype == 1 ? true : false;
        }

        this.haveData();
        _easyRefreshController.finishRefresh();
        return;
      }

      ///上拉加载
      if (null != data &&
          data.data.result != null &&
          data.data.result.length > 0) {
        _entity.data.result.addAll(data.data.result);
        setState(() {});
        _easyRefreshController.finishLoad();
        return;
      }
      _easyRefreshController.finishLoad();
      ToastUtil.showShortToast("没有更多了");
      return;
    }, (errMsg) {
      noData();
      ToastUtil.showShortErrToast(errMsg);
    });
  }

  /* getStatus() {
    if (widget.index == 1) {
      return "A";
    } else if (widget.index == 2) {
      return "B";
    } else if (widget.index == 3) {
      return "C";
    } else if (widget.index == 4) {
      return "D";
    }
    return "";
  }*/

  getItem(TaskListDataResult result) {
    return InkWell(
      onTap: () {
        NavigatorUtils.pushResult(
            context, "${Routes.taskDetail}?id=${result.id}", (rest) {});
      },
      child: Container(
        margin: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(30),
            ScreenUtil().setWidth(10),
            ScreenUtil().setWidth(30),
            ScreenUtil().setWidth(10)),
        padding: EdgeInsets.all(ScreenUtil().setWidth(20)),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(6),
        ),
        child: Column(
          children: <Widget>[
            getRow1(result),
            getRow2(result),
            getRow3(result),
          ],
        ),
      ),
    );
  }

  getRow1(TaskListDataResult result) {
    List<Widget> lists = [];
    lists.add(ClipRRect(
      borderRadius: BorderRadius.circular(6),
      child: UiUtils.cachedNetworkImage(40, 40, result.pic),
    ));
    lists.add(Expanded(
        flex: 1,
        child: Container(
          margin: EdgeInsets.only(left: ScreenUtil().setWidth(10)),
          child: Text(result.name,
              style: TextStyles.custom(
                  28, Colours.appC2, Font.PingFangMedium)),
        )));

    if (result.zb != "" && result.zb != "0") {
      lists.add(Container(
        margin: EdgeInsets.only(right: ScreenUtil().setWidth(10)),
        padding: EdgeInsets.fromLTRB(
            ScreenUtil().setWidth(5), 0, ScreenUtil().setWidth(5), 0),
        decoration: BoxDecoration(border: Border.all(color: Colours.appC10)),
        child: Text("直播",
            style: TextStyles.custom(
                28, Colours.appC10, Font.PingFangMedium)),
      ));
    }

    lists.add(Container(
      padding: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(5), 0, ScreenUtil().setWidth(5), 0),
      decoration: BoxDecoration(border: Border.all(color: Colours.appC10)),
      child: Text(result.taskStart,
          style: TextStyles.custom(
              28, Colours.appC10, Font.PingFangMedium)),
    ));
    lists.add(Container(
      margin: EdgeInsets.only(left: ScreenUtil().setWidth(10)),
      padding: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(5), 0, ScreenUtil().setWidth(5), 0),
      decoration:
          BoxDecoration(border: Border.all(color: Colours.appC095105239)),
      child: Text(result.categoryName == "电商任务" ? "垫付" : "浏览",
          style: TextStyles.custom(
              28, Colours.appC095105239, Font.PingFangMedium)),
    ));

    return Container(
      child: Row(
        children: lists,
      ),
    );
  }

  String getName(String storeName) {
    List<String> list = storeName.split("");
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < list.length; i++) {
      if ((i + 1) % 2 == 1) {
        sb.write(list[i]);
        if (i != list.length - 1) {
          sb.write("*");
        }
      }
    }
    return sb.toString();
  }

  getRow2(TaskListDataResult result) {
    return Container(
      margin: EdgeInsets.only(top: ScreenUtil().setWidth(30)),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[
          RealRichText([
            TextSpan(
              text: "${result.price}金",
              style: TextStyles.custom(
                  40, Colours.appC16, Font.PingFangBlod),
            ),
            TextSpan(
              text: "  预付金额:${result.priceGoods}元",
              style: TextStyles.custom(
                  26, Colours.appC2, Font.PingFangMedium),
            )
          ]),
        ],
      ),
    );
  }

  getRow3(TaskListDataResult result) {
    return Container(
      margin: EdgeInsets.only(top: ScreenUtil().setWidth(26)),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[
          RealRichText([
            TextSpan(
              text: "截止时间：",
              style: TextStyles.custom(
                  26, Colours.appC3, Font.PingFangRegular),
            ),
            TextSpan(
              text: "  ${result.timeEnd}",
              style: TextStyles.custom(
                  26, Colours.appC3, Font.PingFangRegular),
            )
          ]),
          Expanded(
            flex: 1,
            child: Container(
              alignment: Alignment.centerRight,
              child: Text(
                "剩余${result.remainNum}次",
                style: TextStyles.custom(
                    26, Colours.appC3, Font.PingFangRegular),
              ),
            ),
          )
        ],
      ),
    );
  }

  FormData getFormData(int page) {
    //全部
    var category = "";
    var plat = "";
    var taskId = "";

    //淘宝
    if (widget.index == 1) {
      category = "1";
      plat = "1";
    }
    //京东
    if (widget.index == 2) {
      category = "1";
      plat = "2";
    }
    //拼多多
    if (widget.index == 3) {
      category = "1";
      plat = "3";
    }

    //浏览
    if (widget.index == 4) {
      category = "4";
      plat = "";
    }

    return FormData.from({
      "category": category,
      "plat": plat,
      "page": page,
      "size": "10",
      "task_id": taskId
    });
  }

  void getAccount() {
    DioManager.getInstance().get(Api.TASK_TESTACCOUNT, null, (json) {
      TestaccountEntity entity = TestaccountEntity.fromJson(json);
      if (null != entity && entity.code == 200) {
        StringBuffer sb = new StringBuffer();
        entity.data.forEach((TestaccountData item) {
          if (item.type == 0) {
            sb.write("【${item.name}】");
          }
        });

        if (sb.toString().isNotEmpty) {
          showElasticDialog(
              context: context,
              builder: (BuildContext context) {
                return JudjeDialog(
                  title: "发现账号未绑定",
                  value:
                      "系统检测到您还没绑定${sb.toString()}账号，请绑定后查看${sb.toString()}任务",
                  onPressed: () {
                    prefix0.NavigatorUtils.goBack(context);
                    NavigatorUtils.push(
                        context, "${Routes.taoList}?isFromTask=1");
                  },
                );
              });
        }
      }
    }, (err) {});
  }

  bool visible = false;

  _ContentWithZb(Widget widget) {
    return Container(
      child: Column(
        children: <Widget>[
          Offstage(
            offstage: visible,
            child: Container(
              padding: EdgeInsets.fromLTRB(
                  0, ScreenUtil().setWidth(30), 0, ScreenUtil().setWidth(30)),
              color: Colours.c255222223,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Padding(
                    padding: EdgeInsets.only(left: ScreenUtil().setWidth(30)),
                  ),
                  Expanded(
                    child: Text(
                      "下一场直播时间${_entity.data.isZb.zbtime},请不要错过哦~\n"
                        "直播但不限制结单数量，只要看到的都能接,请放行做单",
                      textAlign: TextAlign.center,
                      style: TextStyles.custom(
                          24, Colours.appC10, Font.PingFangMedium),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      setState(() {
                        visible = true;
                      });
                    },
                    child: Container(
                      padding:
                          EdgeInsets.only(right: ScreenUtil().setWidth(30)),
                      height: ScreenUtil().setWidth(30),
                      width: ScreenUtil().setWidth(50),
                      child: Image.asset(Utils.getImgPath("icon_delete")),
                    ),
                  )
                ],
              ),
            ),
          ),
          Expanded(
            child: widget,
          )
        ],
      ),
    );
  }

  _listView() {
    return EasyRefresh.custom(
      controller: _easyRefreshController,
      shrinkWrap: false,

      /// firstRefresh: true,
      enableControlFinishRefresh: true,
      enableControlFinishLoad: true,
      header: BallPulseHeader(),
      footer: BallPulseFooter(),
      onRefresh: () async {
        await Future.delayed(Duration(seconds: 1), () {
          _currentPage = 1;
          this.getData(page: _currentPage);
        });
      },
      onLoad: () async {
        await Future.delayed(Duration(seconds: 1), () {
          if (_currentPage < _pages) {
            _currentPage++;
            this.getData(page: _currentPage);
          } else {
            _easyRefreshController.finishLoad();
            ToastUtil.showShortToast("没有更多了");
          }
        });
      },
      slivers: <Widget>[
        SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              return this.getItem(_entity.data.result[index]);
            },
            childCount: _entity.data.result.length,
          ),
        ),
      ],
    );
  }
}
